<template>
  <el-input-number
    v-model="localValue"
    :placeholder="param.placeholder || `请输入${param.paramName}`"
    :precision="param.precision || 0"
    :step="getStep(param.precision)"
    :min="getMinValue"
    :max="getMaxValue"
    controls-position="right"
    size="medium"
    style="width: 100%"
    @change="handleChange"
    @blur="validate"
  ></el-input-number>
</template>

<script>
export default {
  name: 'NumberInput',
  props: {
    value: {
      type: [Object, String, Number],
      required: true
    },
    param: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      localValue: null,
      lastEmittedValue: null // 记录上次发射的值，避免重复触发
    }
  },
  computed: {
    getMinValue() {
      return this.param.min !== undefined ? Number(this.param.min) : -Infinity
    },

    getMaxValue() {
      return this.param.max !== undefined ? Number(this.param.max) : Infinity
    }
  },
  watch: {
    value: {
      handler(newVal) {
        console.log('NumberInput - 值变化:', {
          param: this.param.paramName,
          新值: newVal,
          类型: typeof newVal
        })

        const processedValue = this.processIncomingValue(newVal)
        
        // 只有值真正变化时才更新 localValue
        if (processedValue !== this.localValue) {
          this.localValue = processedValue
          console.log('NumberInput - 更新 localValue:', this.localValue)
        }
      },
      immediate: true,
      deep: true
    },

    // 监听 localValue 变化，用于调试
    localValue(newVal) {
      console.log('NumberInput - localValue 变化:', {
        param: this.param.paramName,
        newVal
      })
    }
  },
  methods: {
    // 处理传入的值
    processIncomingValue(value) {
      console.log('NumberInput - 处理传入值:', value)
      
      if (value === null || value === undefined) {
        return null
      }

      // 处理对象格式 { value: '', isValid: true, message: '' }
      if (typeof value === 'object') {
        if (value.value === '' || value.value === null || value.value === undefined) {
          return null
        }
        const numValue = Number(value.value)
        return isNaN(numValue) ? null : numValue
      }

      // 处理字符串或数字
      if (value === '') {
        return null
      }
      
      const numValue = Number(value)
      return isNaN(numValue) ? null : numValue
    },

    getStep(precision) {
      if (precision === 0) return 1
      if (precision === 1) return 0.1
      if (precision === 2) return 0.01
      return Math.pow(10, -precision)
    },

    handleChange(value) {
      console.log('NumberInput - handleChange:', {
        param: this.param.paramName,
        value,
        localValue: this.localValue
      })
      
      // 避免重复触发相同值的变更
      if (value === this.lastEmittedValue) {
        console.log('NumberInput - 值未变化，跳过发射')
        return
      }
      
      this.lastEmittedValue = value
      this.emitChange(value, true, '')
    },

    validate() {
      const value = this.localValue
      let isValid = true
      let message = ''

      console.log('NumberInput - 验证:', {
        param: this.param.paramName,
        value,
        required: this.param.required
      })

      // 必填验证
      if (this.param.required && (value === null || value === '' || isNaN(value))) {
        isValid = false
        message = this.param.validationMessage?.required || '此字段为必填项'
        console.log('NumberInput - 必填验证失败')
      }

      // 数值验证（只有在有值且不是NaN时验证）
      if (isValid && value !== null && !isNaN(value)) {
        console.log('NumberInput - 进行数值范围验证:', {
          value,
          min: this.param.min,
          max: this.param.max
        })
        
        // 最小值验证
        if (this.param.min !== undefined && value < Number(this.param.min)) {
          isValid = false
          message = this.param.validationMessage?.min || `数值不能小于 ${this.param.min}`
          console.log('NumberInput - 最小值验证失败')
        }
        
        // 最大值验证
        if (this.param.max !== undefined && value > Number(this.param.max)) {
          isValid = false
          message = this.param.validationMessage?.max || `数值不能大于 ${this.param.max}`
          console.log('NumberInput - 最大值验证失败')
        }
        
        // 精度验证
        if (this.param.precision !== undefined) {
          const decimalPart = value.toString().split('.')[1]
          if (decimalPart && decimalPart.length > this.param.precision) {
            isValid = false
            message = `数值精度不能超过 ${this.param.precision} 位小数`
            console.log('NumberInput - 精度验证失败')
          }
        }
      }

      console.log('NumberInput - 验证结果:', { isValid, message })
      this.emitChange(value, isValid, message)
    },
    
    emitChange(value, isValid, message) {
      // 处理 el-input-number 返回 undefined 的情况
      const finalValue = value === undefined ? null : value
      
      const result = {
        value: finalValue,
        isValid,
        message
      }
      
      console.log('NumberInput - 发射变化:', {
        param: this.param.paramName,
        result
      })
      
      this.$emit('change', result)
    }
  }
}
</script>